package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import compile.Answer;
import compile.ExitCode;
import compile.Question;
import compile.Task;
import dao.Problem;
import dao.ProblemDAO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

/**
 * @author hewen
 */
@WebServlet("/compile")
public class CompileServlet extends HttpServlet {
    static class CompileRequest {
        public int id;
        public String code;
    }

    static class CompileResponse {
        public ExitCode exitCode;
        public String reason;
        public String stdout;
    }
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setStatus(200);
        resp.setContentType("application/json;charset=utf8");
        // 1、准备Solution.java代码
        String body = readBody(req);
        CompileRequest compileRequest = objectMapper.readValue(body, CompileRequest.class);
        String committedCode = compileRequest.code; // 用户提交的代码
        ProblemDAO problemDAO = new ProblemDAO();
        String testCode = problemDAO.getTestCasesForTheTopic(compileRequest.id); // 从数据读取题目的测试代码
        String finalCode = mergeCode(committedCode,testCode); // 合并代码
        // 2、创建task对象完成编译运行
        Task task = new Task();
        Question question = new Question();
        question.setCode(finalCode);
        Answer answer = task.compileAndRun(question);
        CompileResponse compileResponse = new CompileResponse();
        compileResponse.exitCode = answer.getExitCode();
        compileResponse.reason = answer.getReason();
        compileResponse.stdout = answer.getStdout();
        String respString = objectMapper.writeValueAsString(compileResponse);
        resp.getWriter().write(respString);

    }

    private String mergeCode(String requestCode, String testCode) {
        String newCode = removeComments(requestCode);
        return newCode.substring(0,newCode.length()-1)+testCode+"\n}";
    }

    private String readBody(HttpServletRequest req) throws UnsupportedEncodingException {
        // 1、根据请求头的 ContentLength 获取body的长度
        // 2、准备一个byte[]数组
        // 3、获取body的流对象
        // 4、基于流对象读取内容
        // 5、toString()
        int contentLength = req.getContentLength();
        byte[] buffer = new byte[contentLength];
        try(InputStream inputStream = req.getInputStream()){
            inputStream.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // java中字节与字符以及编码格式的知识。

        return new String(buffer, "utf8");
    }
    public static String removeComments(String code) {
        return code.replaceAll(
                "/\\*([\\s\\S]*?)\\*/|//.*?(?=\\n|$)",
                ""
        ).replaceAll("\\n+", "\n").trim();
    }


}
